/*
Copyright (C) Huawei Technologies Co., Ltd. 2015. All rights reserved.
See LICENSE.txt for this sample's licensing information.
*/

package com.PP.fish.huawei;

import java.text.DateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import java.util.regex.Pattern;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
import android.widget.Toast;

import com.android.huawei.pay.plugin.IPayHandler;
import com.android.huawei.pay.plugin.PayParameters;
import com.huawei.gamebox.buoy.sdk.impl.BuoyOpenSDK;
import com.huawei.gamebox.buoy.sdk.inter.UserInfo;
import com.huawei.gamebox.buoy.sdk.util.DebugConfig;
import com.huawei.hwid.openapi.OpenHwID;
import com.huawei.opensdk.OpenSDK;
import com.unity3d.player.UnityPlayer;
import com.unity3d.player.UnityPlayerActivity;

public class MainActivity extends UnityPlayerActivity
{
    
    // 日志标签
    public static final String TAG = "MainActivity";
    public static final String TAGAndroid = "Android";
    public static Map<String, String> param = new HashMap<String, String>();
    // 返回键是否可用

    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
    }
    
    protected void onNewIntent(Intent intent) {
		super.onNewIntent(intent);
		
		setIntent(intent);
		String value=intent.getStringExtra("from");
        Log.v(TAGAndroid, "收到Intent2222===="+value+value.equals("changeuserinfo"));
        if(value.equals("changeuserinfo")){
        	//Start();
        	ChanggeLogin();
        	Log.v(TAGAndroid, "重新登錄2222");
        }
	}
    
    public static boolean isInMainThread() {
        return Looper.myLooper() == Looper.getMainLooper();
  }
    protected void onResume() { 
    	super.onResume(); 
    // 在界面恢复的时候又显示浮标，和onPause配合使用 
    	BuoyOpenSDK.getIntance().showSmallWindow(MainActivity.this);
    }
    protected void onPause() { 
    	super.onPause(); 
    	// 在界面暂停的时候，隐藏浮标，和onResume配合使用
	    BuoyOpenSDK.getIntance().hideSmallWindow(this); 
	    BuoyOpenSDK.getIntance().hideBigWindow(this); 
    }
    
    protected void onDestroy()
    {
        super.onDestroy();
        // 仅当MainActivity为最后一个Activity时，才释放资源
        if (isTaskRoot())
        {
            // 清空帐号资源
            OpenHwID.releaseResouce();
            // 在退出的时候销毁浮标
            BuoyOpenSDK.getIntance().destroy(this);
        }
        
    }
    //初始化回调
    private UserInfo loginCallBack=new UserInfo(){

	@Override
	 public void dealUserInfo(HashMap<String, String> userInfo)
    {
        //TextView loginPageTips = (TextView)findViewById(R.id.page1);
        Log.v(TAG, "登录成功，回调Unity----dealUserInfo");
        // 用户信息为空，登录失败
        if (null == userInfo)
        {
            //loginPageTips.setText("用户信息为null");
        }
        // 使用华为账号登录且成功，进行accessToken验证
        else if ("1".equals((String)userInfo.get("loginStatus")))
        {
            //loginPageTips.setText("使用华为账号登录，进行accessToken校验");
            
            // 进行accessToken校验
        	
            param.put("accessToken", (String)userInfo.get("accesstoken"));
            param.put("userID", (String)userInfo.get("userID"));
            Log.v(TAGAndroid, "============"+(String)userInfo.get("userID"));
            // 此处禁用返回键，防止校验accessToken完成前退出当前Activity，CP可以用等待框等其他方式处理
            // 校验accessToken完成以后恢复返回键可用
            new Thread(new Runnable(){
        		public void run(){
        			try {
    					Thread.sleep(1000);
    					handler.sendEmptyMessage(1);
    				} catch (InterruptedException e1) {
    					// TODO Auto-generated catch block
    					e1.printStackTrace();
    				}
        		}
        		
        	}).start();	
            LoginCallback((String)userInfo.get("accesstoken"));
            
        }
    }
};
    public void Init(String APP_ID,String CP_ID,String privateKeyCons){
    	

        // 开启浮标的日志功能，发布时去掉
        DebugConfig.setLog(true);
        GlobalParam.APP_ID=APP_ID;
        GlobalParam.CP_ID=CP_ID;
        GlobalParam.BUO_SECRET=privateKeyCons;
        
        
        Log.v(TAG, "初始化参数==="+GlobalParam.APP_ID+GlobalParam.CP_ID+GlobalParam.BUO_SECRET);
        // 为了安全把浮标密钥放到服务端，并使用https的方式获取下来存储到内存中，CP可以使用自己的安全方式处理
        //getBuoyPrivate.execute();
        int retCode = OpenSDK.init(
                MainActivity.this,
                GlobalParam.APP_ID,
                GlobalParam.CP_ID,
                GlobalParam.BUO_SECRET,
                loginCallBack);
        DebugConfig.d(TAG, "OpenSDK init retCode is:" + retCode);
        InitCallback(Integer.toString(retCode));
    }
    
  
    private Handler handler=new Handler(){
		public void handleMessage(Message msg){
			if(msg.what==0){
				OpenSDK.start();
				Log.v(TAGAndroid, "Start Over");
			}else if(msg.what == 1){//显示悬浮窗
				Log.e(TAGAndroid, "调用浮标显示");
				BuoyOpenSDK.getIntance().showSmallWindow(MainActivity.this);
				Log.v(TAGAndroid, "Start Over"+isInMainThread());
			}else if(msg.what == 2){//支付
				//startPay();
				String[] data=new String[6];
				data=(String[])msg.obj;
				startPay(data[0],data[1],data[2],param.get("userID")+"|"+data[2]+"|"+data[5],data[3],data[4]);
			}
			
		}
	};
    public void Start(){
    	Log.v(TAGAndroid, "Start");
    	new Thread(new Runnable(){
    		public void run(){
    			try {
					Thread.sleep(1000);
					handler.sendEmptyMessage(0);
				} catch (InterruptedException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				}
    		}
    		
    	}).start();	
    }
    //------------------------------------------------------
    public void Pay(final String price,final String productName,final String productDesc,
    		final String PAY_ID,final String sign,final String RequestId){
    	
    	//final String price=(String)param[0];
    	//final String productName=(String)param[1];
    	//final String productDesc=(String)param[2];
    	
    	GlobalParam.PAY_ID=PAY_ID;
    	//GlobalParam.PAY_RSA_PRIVATE=PAY_RSA_PRIVATE;
    	//GlobalParam.PAY_RSA_PUBLIC=PAY_RSA_PUBLIC;
    	
    	
    	Log.v(TAGAndroid, "Pay==="+price+"---"+productName+"----"+productDesc);
    	new Thread(new Runnable(){
    		public void run(){
    			try {
    				Thread.sleep(1000);
    				String[] data=new String [6];
    				data[0]=price;
    				data[1]=productName;
    				data[2]=productDesc;
    				
    				data[3]=sign;
    				data[4]=RequestId;
    				data[5]=GlobalParam.APP_ID;
    				
    				Message msg=Message.obtain();
    				msg.obj=data;
    				msg.what=2;
					
					handler.sendMessage(msg);
				} catch (InterruptedException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				}
    		}
    		
    	}).start();	
    	
    	
    }
    private void startPay(String price,String productName,String productDesc,String extReserved,final String sign,final String RequestId){
    	
    	DateFormat format = new java.text.SimpleDateFormat("yyyy-MM-dd-hh-mm-ss-SSS", Locale.US);
    	String requestId  = format.format(new Date());
    	//price=price+".00";
    	boolean priceChceckRet = Pattern.matches("^\\d+[.]\\d{2}$", price);
        if (!priceChceckRet)
        {
            Toast.makeText(getApplicationContext(), "价格必填且精确到小数点后两位", Toast.LENGTH_SHORT).show();
            return;
        }
        
        if ("".equals(productName))
        {
            Toast.makeText(getApplicationContext(), "道具名称必填", Toast.LENGTH_SHORT).show();
            return;
        }
        // 禁止输入：# " & / ? $ ^ *:) \ < > | , =
        else if (Pattern.matches(".*[#\\$\\^&*)=|\",/<>\\?:].*", productName))
        {
            Toast.makeText(getApplicationContext(), "道具名称不能存在  #$^&*)=|\",/<>\\?:", Toast.LENGTH_LONG).show();
            return;
        }
        // 禁止输入：# " & / ? $ ^ *:) \ < > | , =
        if ("".equals(productDesc))
        {
            Toast.makeText(getApplicationContext(), "道具描述必填", Toast.LENGTH_SHORT).show();
            return;
        }
        // 禁止输入：# " & / ? $ ^ *:) \ < > | , =
        else if (Pattern.matches(".*[#\\$\\^&*)=|\",/<>\\\\?\\^:].*", productDesc))
        {
            Toast.makeText(getApplicationContext(), "道具描述不能存在  #$^&*)=|\",/<>\\?:", Toast.LENGTH_LONG).show();
            return;
        }
        
        // 调用公共方法进行支付
        GameBoxUtil.startPay(MainActivity.this, price, productName, productDesc, requestId, payHandler,extReserved,sign,RequestId);
    }
    private IPayHandler payHandler = new IPayHandler()
    {
        @Override
        public void onFinish(Map<String, String> payResp)
        {
            DebugConfig.d(TAG, "支付结束：payResp= " + payResp);
            // 处理支付结果
            String pay = "支付未成功！";
            DebugConfig.d(TAG, "支付结束，返回码： returnCode=" + payResp.get(PayParameters.returnCode));
            // 支付成功，进行验签
            
            
            if ("0".equals(payResp.get(PayParameters.returnCode)))
            {
                if ("success".equals(payResp.get(PayParameters.errMsg)))
                {
                    // 支付成功，验证信息的安全性；待验签字符串中如果有isCheckReturnCode参数且为yes，则去除isCheckReturnCode参数
                    if (payResp.containsKey("isCheckReturnCode") && "yes".equals(payResp.get("isCheckReturnCode")))
                    {
                        payResp.remove("isCheckReturnCode");
                        
                    }
                    else
                    {// 支付成功，验证信息的安全性；待验签字符串中如果没有isCheckReturnCode参数活着不为yes，则去除isCheckReturnCode和returnCode参数
                        payResp.remove("isCheckReturnCode");
                        payResp.remove(PayParameters.returnCode);
                    }
                    
                    pay = "支付成功！";
                    PayCallback("0");
                    
                }
                else
                {
                	PayCallback("2");
                    DebugConfig.d(TAG, "支付失败 errMsg= " + payResp.get(PayParameters.errMsg));
                }
            }
            else if ("30002".equals(payResp.get(PayParameters.returnCode)))
            {
                pay = "支付结果查询超时！";
                PayCallback("3");
            }
            else if("200001".equals(payResp.get(PayParameters.returnCode))){
            	
            	PayCallback("4");
            }
            DebugConfig.d(TAG, " 支付结果 result = " + pay);
        }
    };
    private void InitCallback(String code){
    	Log.v(TAGAndroid, "Android InitCallback");
    	
    	
    	UnityPlayer.UnitySendMessage("Main Camera", "InitCallback", code);
    }
    
    private void LoginCallback(String msg){
    	
    	UnityPlayer.UnitySendMessage("Main Camera", "LoginCallback", msg);
    }
    private void PayCallback(String msg){
    	Log.v(TAGAndroid, "Android PayCallback");
    	
    	UnityPlayer.UnitySendMessage("Main Camera", "PayCallback", msg);
    }
    private void ChanggeLogin(){
    	Log.v(TAGAndroid, "Android ChanggeLogin");
    	UnityPlayer.UnitySendMessage("Main Camera", "ChanggeLogin","");
    }
}
